package com.wondertek.service.sdk.iotdh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wondertek.common.exception.AppException;
import com.wondertek.common.constant.LanguageCodeStatus;
import com.wondertek.service.sdk.iotdh.dto.req.DeptDeleteReq;
import com.wondertek.service.sdk.iotdh.dto.req.DeptListReq;
import com.wondertek.service.sdk.iotdh.config.SdkConfig;
import com.wondertek.service.sdk.iotdh.constant.SdkUrlConstant;
import com.wondertek.service.sdk.iotdh.dto.req.DeptAddDhReq;
import com.wondertek.service.sdk.iotdh.dto.req.TokenGetDhReq;
import com.wondertek.service.sdk.iotdh.dto.res.TokenGetDhRes;
import com.wondertek.service.sdk.iotdh.service.DhSdkService;
import com.wondertek.service.sdk.iotdh.util.SdkUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class DhSdkServiceImpl implements DhSdkService {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private SdkConfig sdkConfig;

    @Resource
    private SdkUtil sdkUtil;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    //大华请求token key
    private static final String DH_SDK_TOKEN_KEY = "DH_SDK_TOKEN";

    @Override
    public String getToken() {
//        if (Boolean.TRUE.equals(redisTemplate.hasKey(DH_SDK_TOKEN_KEY))) {
//            Object res = redisTemplate.opsForValue().get(DH_SDK_TOKEN_KEY);
//            if(null != res){
//                return res.toString();
//            }
//        }

        long time = System.currentTimeMillis();
        String nonce = generateRandomString(11);
        String sign = sdkUtil.createSign(time,nonce,sdkConfig);
        if(ObjectUtil.isEmpty(sign)){
            throw new AppException("sign.error");
        }

        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        headers.add("Accept-Language","zh-cn");
        TokenGetDhReq req = new TokenGetDhReq();
        req.setClientId(sdkConfig.getClientId());
        req.setTime(time);
        req.setNonce(nonce);
        req.setSign(sign);

        String jsonData = JSONObject.toJSONString(req);
        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);
        System.out.println(sdkConfig.getBaseUrl().concat(SdkUrlConstant.GET_TOKEN));
        ResponseEntity<String> exchange = restTemplate.exchange(sdkConfig.getBaseUrl().concat(SdkUrlConstant.GET_TOKEN),
                HttpMethod.POST, entity, String.class);

        if(!Objects.equals(200,exchange.getStatusCodeValue())){
            throw new AppException("token.error");
        }
        TokenGetDhRes tokenGetDhRes = JSONObject.parseObject(exchange.getBody(), TokenGetDhRes.class);
        String bearer_token = tokenGetDhRes.getToken_type()+" "+tokenGetDhRes.getAccess_token();
        redisTemplate.opsForValue().set(DH_SDK_TOKEN_KEY, bearer_token,
                tokenGetDhRes.getExpires_in(), TimeUnit.SECONDS);

        return bearer_token;
    }


    @Override
    public String addDept(DeptAddDhReq req) {
        String token = getToken();
        HttpHeaders headers = getCommonHeaders(token);

        String jsonData = JSONObject.toJSONString(req);
        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);

        ResponseEntity<String> exchange = restTemplate.exchange(sdkConfig.getBaseUrl().concat(SdkUrlConstant.ADD_DEPT),
                HttpMethod.POST, entity, String.class);
        if(!Objects.equals(200,exchange.getStatusCodeValue())){
            throw new AppException("department.add.fail");
        }

        return exchange.getBody();
    }

    @Override
    public String deleteDept(DeptDeleteReq req) {
        String token = getToken();
        HttpHeaders headers = getCommonHeaders(token);

        String jsonData = JSONObject.toJSONString(req);
        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);

        ResponseEntity<String> exchange = restTemplate.exchange(sdkConfig.getBaseUrl().concat(SdkUrlConstant.DELETE_DEPT),
                HttpMethod.POST, entity, String.class);
        if(!Objects.equals(200,exchange.getStatusCodeValue())){
            throw new AppException("接口删除部门失败!");
        }
        return exchange.getBody();
    }

    @Override
    public String listDept(DeptListReq req) {
        String token = getToken();
        HttpHeaders headers = getCommonHeaders(token);

        String jsonData = JSONObject.toJSONString(req);
        HttpEntity<String> entity = new HttpEntity<>(jsonData, headers);

        ResponseEntity<String> exchange = restTemplate.exchange(sdkConfig.getBaseUrl().concat(SdkUrlConstant.LIST_DEPT),
                HttpMethod.POST, entity, String.class);
        if(!Objects.equals(200,exchange.getStatusCodeValue())){
            throw new AppException("接口查询部门失败!");
        }
        JSONObject object = JSONObject.parseObject(JSON.toJSONString(exchange.getBody()));
        JSONObject data = JSONObject.parseObject(JSON.toJSONString(object.get("data")));
        JSONArray records = data.getJSONArray("records");
        if(CollectionUtil.isEmpty(records)){
            throw new AppException("未查询到部门!");
        }
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(records.get(0)));
        return jsonObject.getString("orgId");
    }


    /**
     * 获取统一请求头
     */
    private HttpHeaders getCommonHeaders(String token){
        long time = System.currentTimeMillis();
        String nonce = generateRandomString(11);
        String sign = sdkUtil.createSign(time,nonce,sdkConfig);
        if(ObjectUtil.isEmpty(sign)){
            throw new AppException("sign.error");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");
        headers.add("Accept-Language","zh-cn");
        headers.add("clientId",sdkConfig.getClientId());
        headers.add("authorization",token);
        headers.add("timestamp",time + "");
        headers.add("nonce",nonce);
        headers.add("sign",sign);
        return headers;
    }


    private static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            // 可以根据需要调整字符范围
            int randomChar = random.nextInt(26) + 'a';
            sb.append((char) randomChar);
        }
        return sb.toString();
    }
}
